<?php

namespace App\Http\Services;

use App\Http\Dao\CourseTypeDao;
use App\Models\CourseTypeModel;
use App\Models\LabelModel;
use App\Models\QuestionModel;

/**
 * @property CourseTypeDao $courseTypeDao
 */
class CourseTypeService
{

    public function __construct(CourseTypeDao $courseTypeDao)
    {
        $this->courseTypeDao = $courseTypeDao;
    }

    public function getTypeList($sid)
    {
        return $this->courseTypeDao->getList("s_id = '{$sid}'")->toArray();
    }

    public function getTypeDetail($params)
    {
        if (!empty($params['searchValue'])) {
//            $info = CourseTypeModel::query()->with(['subject', 'question' => function ($query) use ($params) {
//                $query->where('question_text', 'like', "%{$params['searchValue']}%");
////                $query->orWhere('answer', 'like', "%{$params['searchValue']}%");
//            }])->first();

            $info['question'] = QuestionModel::query()
                ->where('question_text', 'like', "%{$params['searchValue']}%")
                ->orWhere('answer', 'like', "%{$params['searchValue']}%")
                ->get()->toArray();
            return $info;
        } else {
            $info = CourseTypeModel::query()->with(['question', 'subject'])->where('id', $params['tid'])->first();
            return $info ? $info->toArray() : [];
        }
    }

    public function questionDetail($qid)
    {
        $info = QuestionModel::query()->with(['subject', 'courseType'])->where('id', $qid)->first()->toArray();
        if (!empty($info)) {
            // 最新更新的id
            $lastId = QuestionModel::query()->where('id', '>', $qid)->where('s_id', $info['s_id'])->where('t_id', $info['t_id'])->value('id');
            //获取上一题
            $preId = QuestionModel::query()->where('id', '<', $qid)->where('s_id', $info['s_id'])->where('t_id', $info['t_id'])->orderBy('id','desc')->value('id');
            $info['label'] = LabelModel::query()->whereIn('id', explode(',', $info['s_id']))->select(['id', 'label_name'])->get()->toArray();
            // 题目总数
            $info['count'] = QuestionModel::query()->where('s_id', $info['s_id'])->where('t_id', $info['t_id'])->count();
            // 上一题id
            $info['pre_id'] = $preId ?? 0;
            // 下一题id
            $info['next_id'] = $lastId ?? 0;
            // 题目进度
            $info['progress'] = sprintf('%d', ($info['order'] / $info['count']) * 100);
        }

        return $info;
    }
}
